package com.serviceprovider.business.module.admin.messages.serivces.dao.impl;

//~--- non-JDK imports --------------------------------------------------------

import com.serviceprovider.business.module.admin.action.model.AclAction;
import com.serviceprovider.business.module.admin.messages.model.Message;
import com.serviceprovider.business.module.admin.messages.serivces.dao.interfaces.IMessagesService;
import com.serviceprovider.business.module.admin.role.model.Role;
import com.serviceprovider.business.module.admin.user.model.OldUser;
import com.serviceprovider.business.module.common.Page;
import com.serviceprovider.business.module.common.PaginationHelper;
import com.serviceprovider.business.module.user.model.impl.User;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Service;

//~--- JDK imports ------------------------------------------------------------

import java.sql.ResultSet;
import java.sql.SQLException;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("messageService")
public class MessagesServiceImpl extends JdbcDaoSupport implements IMessagesService {
    protected final Log logger = LogFactory.getLog(getClass());

    @Autowired
    public MessagesServiceImpl(@Qualifier("jdbcTemplate") JdbcTemplate jdbcTemplate) {
        setJdbcTemplate(jdbcTemplate);
    }

    @Override
    public Message getById(int id) {
        RowMapper mapper = new RowMapper() {
            public Message mapRow(ResultSet rs, int rowNum) throws SQLException {
                Message message = new Message();

                MessagesServiceImpl.mapRow(message, rs);

                return message;
            }
        };
        final String sql = "select * from messages where id = ?";    // $NON-NLS-1$

        try {
            return (Message) getJdbcTemplate().queryForObject(sql, new Object[] { id }, mapper);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    private static void mapRow(Message message, ResultSet rs) throws SQLException {
        message.setId(rs.getInt("id"));

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date             date;

        try {

            // Code - start
            if (rs.getString("expiryDate") == null) {
                message.setExpiryDate("");
            } else {

                // Code - end
                date = dateFormat.parse(rs.getString("expiryDate"));

                SimpleDateFormat dataFormat2 = new SimpleDateFormat("MM/dd/yyyy");

                message.setExpiryDate(dataFormat2.format(date));

                // Code - start
            }

            // Code - end
        } catch (ParseException e) {
            e.printStackTrace();
        }

        message.setActive(rs.getString("isActive").equals("1"));
        message.setMessageText(rs.getString("messageText"));
        message.setRoleId(rs.getInt("role_id"));
        message.setUserId(rs.getInt("user_id"));
    }

    @Override
    public void delete(int id) {
        String sql = "delete from messages where id = ?";

        getJdbcTemplate().update(sql, new Object[] { id });
    }

    @Override
    public void deleteMany(String ids) {
        String sql = "delete from messages where id in (" + ids + ") ";

        getJdbcTemplate().update(sql);
    }

    /*
     * Returns a page of records.
     */
    @Override
    public Page<Message> getAll(int pageNo, int recordSize, String sortColumn, String sortOrder) {
        PaginationHelper<Message> ph = new PaginationHelper<Message>();

        return ph.fetchPage(getJdbcTemplate(), "SELECT count(*) FROM messages ORDER BY messageText",
                            "SELECT id, messageText,isActive FROM messages order by " + sortColumn + " " + sortOrder,
                            new Object[] {}, pageNo, recordSize, sortColumn, sortOrder,
                            new ParameterizedRowMapper<Message>() {
            public Message mapRow(ResultSet rs, int i) throws SQLException {
                Message msg = new Message();

                msg.setId(rs.getInt(1));
                msg.setMessageText(rs.getString(2));
                msg.setActive(rs.getString("isActive").equals("1"));

                return msg;
            }
        });
    }

    @Override
    public List<Message> getAllActive() {
        return null;
    }

    @Override
    public List<String> getAllForRole(Role role) {
        Date              date       = new Date();
        SimpleDateFormat  dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String            sql        = "select id,messageText  from messages where isActive=1 and role_id=? and expiryDate>=?";
        List              list       = getJdbcTemplate().queryForList(sql, new Object[] { role.getId(), dateFormat.format(date) });
        Map               row        = null;
        ArrayList<String> messages   = new ArrayList<String>();

        for (Object obj : list) {
            row = (Map) obj;
            messages.add((String) row.get("messageText"));
        }

        return messages;
    }

    @Override
    public List<String> getAllForUser(User user) {
        Date              date       = new Date();
        SimpleDateFormat  dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String            sql        = "select id,messageText  from messages where isActive=1 and user_id=? and expiryDate>=?";
        List              list       = getJdbcTemplate().queryForList(sql, new Object[] { user.getId(), dateFormat.format(date) });
        Map               row        = null;
        ArrayList<String> messages   = new ArrayList<String>();

        for (Object obj : list) {
            row = (Map) obj;
            messages.add((String) row.get("messageText"));
        }

        return messages;
    }

    @Override
    public List<String> getAllForUserRole(User user, Role role) {
        Date             date       = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        System.out.println("getting messages before " + dateFormat.format(date));

        String sql =
            "select id,messageText  from messages where isActive=1  and expiryDate>=? and ((user_id=? or role_id=?) or (user_id=-1 and role_id=-1))";
        List list = getJdbcTemplate().queryForList(sql, new Object[] { dateFormat.format(date), user.getId(),
                role.getId() });
        Map               row      = null;
        ArrayList<String> messages = new ArrayList<String>();

        for (Object obj : list) {
            row = (Map) obj;
            messages.add((String) row.get("messageText"));
        }

        return messages;
    }

    @Override
    public List<Message> getAllNotExpired() {
        return null;
    }

    @Override
    public void insert(Message message) {
        String           sql        = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        Date             date;

        try {
            date = dateFormat.parse(message.getExpiryDate());

            SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");

            message.setExpiryDate(dateFormat2.format(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        sql = "Insert into messages (id,role_id, user_id, messageText, expiryDate, isActive) values(null,?,?,?,?,?)";
        getJdbcTemplate().update(sql, new Object[] { message.getRoleId(), message.getUserId(), message.getMessageText(),
                message.getExpiryDate(), message.isActive() });
    }

    @Override
    public void update(Message message) {
        String           sql        = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        Date             date;

        try {
            date = dateFormat.parse(message.getExpiryDate());

            SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");

            message.setExpiryDate(dateFormat2.format(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        sql = "Update messages set role_id=?, user_id=?, messageText=?, expiryDate=?, isActive=?  where id=?";
        getJdbcTemplate().update(sql, new Object[] {
            message.getRoleId(), message.getUserId(), message.getMessageText(), message.getExpiryDate(),
            message.isActive(), message.getId()
        });
    }
}



